#encoding: utf-8
'''
Created on Nov 3, 2016

@author: root
'''
import subprocess
import os
# from exception import OperationFailed

def get_connected_interface():
    connected_iface = []
    ifnames = get_enabled_net_interfaces()
    for ifname in ifnames:
        if is_link_connected(ifname):
            connected_iface.append(ifname)
    return sorted(connected_iface)[0] if connected_iface else None


def is_link_connected(ifname):
    connected = False
    cmd = 'ethtool {0} | grep Duplex'.format(ifname)
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    for line in proc.stdout.readlines():
        if 'Duplex' in line and 'Full' in line:
            connected = True
            break
    return connected


def get_enabled_net_interfaces():
    net_list = os.listdir("/sys/class/net")
    virtule_net_list = os.listdir("/sys/devices/virtual/net/")

    enabled_interfaces_list = list(set(net_list) ^ set(virtule_net_list))

    # check net interface link or not by mii-tool

    return sorted(enabled_interfaces_list)


def config_interface(ifconfig):
    '''
    @param ifconfig: {  "name": "eth0,
                        "type": "static"           # dhcp
                        "address":"192.168.100.21",
                        "network":"192.168.100.0",
                        "netmask":"255.255.225.0",
                        "broadcast":"192.168.100.255",
                        "gateway": "192.168.100.1"
                     }
    '''
    os.system('/etc/init.d/networking stop')
    interface = "auto lo %s iface lo inet loopback %s" %(os.linesep, os.linesep)
    ifname = ifconfig.pop('name')
    net_type = ifconfig.pop('type')
    if net_type == 'dhcp':
        interface += "auto %s%s iface %s inet dhcp %s" % (ifname, os.linesep, ifname, os.linesep)
    else:
        interface += "auto %s%s iface %s inet static%s" % (ifname, os.linesep, ifname, os.linesep)
        for option in ifconfig:
            interface += "%s:%s%s" % (option, ifconfig.get(option), os.linesep)

    with open('/etc/network/interfaces', 'w') as fp:
        fp.write(interface)
    
    command = "/etc/init.d/networking start"
    try:
        os.system(command)
    except Exception as e:
        # raise OperationFailed(e)
        raise Exception(e)


def get_mac(ifname):
    net_address_path = '/sys/class/net/' + ifname + '/address'

    with open(net_address_path) as fp:
        mac_address = fp.read().strip()
        return mac_address    
